""" java libraries """
from java.awt import Color
from java.awt import Font
from java.util import Locale
from java.io import File
from java.text import DecimalFormat
""" jhplot libraries """
from jhplot.jadraw import JaText
from jhplot.jadraw import JaKey
from jhplot  import HPlotJa
from jhplot  import H1D
from jhplot  import F1D
""" Philippe's libraries """
from fr.in2p3.ipnl.aidautilities import AidaUtil
""" jscinttools libraries """
from jscinttools.datafit import DataFitter
from jscinttools.datafit import FitSettings
from jscinttools.datafit import FitFuncFactory
from jscinttools.utilities.aidautilities import AidaFileReader
from jscinttools.utilities.aidautilities import AUtil
from jscinttools.utilities.jhplotutilities import HPlotJaUtil

Locale.setDefault(Locale.ENGLISH) #For French OS
ff = FitFuncFactory.pulseFuncFactory()

showFigures = False
writeFigures = not showFigures

"""
###############################################################
# Define the Path and files names
###############################################################
"""
genPath = "/home/marc-antoine/Documents/ZnWO4/"
aidaPath = ["/Run_5/Reduced/TDC/2011_05_12/", 
		"/Run_6/Reduced/TDC/2011_07_09/", 
		"/Run_6/Reduced/TDC/2011_07_09/", 
		"/Run_6/Reduced/TDC/2011_07_09/", 
		"/Run_6/Reduced/TDC/2011_07_09/"]
aidaFile = ["Am241_3400mK_501", "Am241_3400mK_601", "Am241_3400mK_602", "Am241_3400mK_603", "Am241_3400mK_604"]
outPath = genPath + aidaPath[1]
startPar501 = [0.5, 0.7, 0.04, 31, 0.03, 200, 0.00002]
startPar604 = [0.5, 0.6, 0.05, 25, 0.05, 150, 0.00001]

fitFunc = ff.nExpBck()
win = [0, 1600, 0.00001, 1]
winZoom = [0, 10, 0.01, 1]
title = "Average Pulses of ZnWO_{4} with ^{241}Am at 3.4 K"
preliminary = False
outputFile = "Run6Pulse"
avEvtPath = "Reanalysis/Average pulse shapes/Variable binning/Special Bin, Average Pulse from First Photon on Ch2, Ch1, All Cuts"

""" Define colors and fonts"""
figType = [".png", ".eps", ".pdf"]
colors = [Color.BLUE, Color.RED, Color(0, 170, 0), Color.ORANGE, Color.DARK_GRAY]
axisLabelFont = Font(Font.SERIF, Font.PLAIN, 25)
titleFont = Font(Font.SERIF, Font.PLAIN, 25)
legendFont = Font(Font.SERIF, Font.PLAIN, 22)
ticFont = Font(Font.SERIF, Font.PLAIN, 20)
statBoxFont = Font(Font.SERIF, Font.PLAIN, 15)
prelimFont = Font(Font.SERIF, Font.BOLD, 30)

afr = []
avEvtHist = []
pulse = []
key = []
loop = len(aidaFile)
for i in range(loop):
	afr.append(AidaFileReader(genPath + aidaPath[i], aidaFile[i] + "_PhotonReanalysis_NoTuples"))
	avEvtHist.append(afr[i].grabHisto1D(avEvtPath))
	normFac = avEvtHist[i].maxBinHeight() * 1.0
	avEvtHist[i].scale(1.0 / normFac)
	
	""" Create the plottable jhplot objects from AIDA IObjects"""
	titleLeg = aidaFile[i] .split("K_")[1]
	pulse.append(H1D(avEvtHist[i]))
	pulse[i].setTitle(titleLeg)
	pulse[i].setStyle("h")
	pulse[i].setColor(colors[i])
	pulse[i].setPenWidth(2)
	pulse[i].setErrAll(False)
	
	key.append(JaKey(20, titleLeg, 0.2, 0.6 + (i * 0.05), "NDC"))
	key[i].setColor(pulse[i].getColor())
	key[i].setKeyColor(pulse[i].getColor())
	key[i].setFont(legendFont)
	key[i].setPenWidth(2)
	
	
	
df = DataFitter(fitFunc)
fmt = DecimalFormat("#.#");
fmtSc = DecimalFormat("0.#E0");

#run = ["501", "604"]
#for i in range(len(run)):
#	fs + run[i] = FitSettings(startPar + run[i])
#	fitRes + run[i] = df.doFit(avEvtHist[0], fs + run[i])
#	print(AidaUtil.printResultsOfFit(fitRes + run[i]))
#	
#	func + run[i] = fitRes + run[i].fittedFunction()
#	
#	fit + run[i] = F1D(func + run[i], win[0], win[1])
#	fit + run[i].setColor(Color.CYAN)
#	fit + run[i].setPenWidth(2)
#	fit + run[i].setPoints(1000)
#	
#	fitZoom + run[i] = F1D(func + run[i], winZoom[0], winZoom[1])
#	fitZoom + run[i].setColor(fit + run[i].getColor())
#	fitZoom + run[i].setPenWidth(2)
#	fitZoom + run[i].setPoints(1000)
#	
#	fitResVal + run[i] = fitRes + run[i].fittedParameters()[5]
#	fitResValErr + run[i] = fitRes + run[i].errors()[5]
#	fitResValF + run[i] = fmt.format(fitResVal + run[i])
#	fitResValErrF + run[i] = fmt.format(fitResValErr + run[i])
#	fitResStr + run[i] = fit + run[i].getTitle() + "=" + fitResValF + run[i] + "&plusmn;" + fitResValErrF + run[i] + " &micro;s"
#	statBox + run[i] = JaText(fitResStr + run[i], 0.15, 0.23 + (i * 0.5), "NDC")
#	statBox + run[i].setFont(legendFont)
#	statBox + run[i].setColor(Color.BLUE)

fs501 = FitSettings(startPar501)
fitRes501 = df.doFit(avEvtHist[0], fs501)
print(AidaUtil.printResultsOfFit(fitRes501))
func501 = fitRes501.fittedFunction()
fit501 = F1D(func501, win[0], win[1])
fit501.setTitle("&tau;_{501}")
fit501.setColor(Color.CYAN)
fit501.setPenWidth(2)
fit501.setPoints(1000)
fitZoom501 = F1D(func501, winZoom[0], winZoom[1])
fitZoom501.setTitle("&tau;_{501}")
fitZoom501.setColor(fit501.getColor())
fitZoom501.setPenWidth(2)
fitZoom501.setPoints(1000)
fitResVal501 = fitRes501.fittedParameters()[5]
fitResValErr501 = fitRes501.errors()[5]
fitResValF501 = fmt.format(fitResVal501)
fitResValErrF501 = fmt.format(fitResValErr501)
fitResStr501 = fit501.getTitle() + "=" + fitResValF501 + "&plusmn;" + fitResValErrF501 + " &micro;s"
statBox501 = JaText(fitResStr501, 0.15, 0.23, "NDC")
statBox501.setFont(legendFont)
statBox501.setColor(Color.BLUE)

fs604 = FitSettings(startPar604)
fitRes604 = df.doFit(avEvtHist[4], fs604)
print(AidaUtil.printResultsOfFit(fitRes604))
func604 = fitRes604.fittedFunction()
fit604 = F1D(func604, win[0], win[1])
fit604.setTitle("&tau;_{604}")
fit604.setColor(Color.LIGHT_GRAY)
fit604.setPenWidth(2)
fit604.setPoints(1000)
fitZoom604 = F1D(func604, winZoom[0], winZoom[1])
fitZoom604.setTitle("&tau;_{604}")
fitZoom604.setColor(fit604.getColor())
fitZoom604.setPenWidth(2)
fitZoom604.setPoints(1000)
fitResVal604 = fitRes604.fittedParameters()[5]
fitResValErr604 = fitRes604.errors()[5]
fitResValF604 = fmt.format(fitResVal604)
fitResValErrF604 = fmt.format(fitResValErr604)
fitResStr604 = fit604.getTitle() + "=" + fitResValF604 + "&plusmn;" + fitResValErrF604 + " &micro;s"
statBox604 = JaText(fitResStr604, 0.15, 0.28, "NDC")
statBox604.setFont(legendFont)
statBox604.setColor(Color.DARK_GRAY)


prelim = JaText("PRELIMINARY", 0.05, 0.35, "NDC")
prelim.setFont(prelimFont)
prelim.setColor(colors[1])
prelim.setRotAngle(-45)

"""
###############################################################
# Plotting Part
###############################################################
"""

""" Create the Plotter"""
plotter = HPlotJa("Average Event", 600, 600, 2, 1, True)
plotter.setGTitle(title, titleFont)
plotter.setAntiAlias(False)

plotter.cd(1,1)	
plotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
plotter.setRange(win[0], win[1], win[2], win[3])
plotter.setLogScale(0, False)
plotter.setLogScale(1, True)
plotter.setTicFont(ticFont)
plotter.setShowStatBox(False)
plotter.showKey(False)
plotter.setNameX("Time (&micro;s)")
plotter.setNameY("Photons / Time Unit")

plotter.cd(2,1)	
plotter.setPad(2, 1, 0.525, 0.17, 0.3, 0.3)
plotter.setRange(winZoom[0], winZoom[1], winZoom[2], winZoom[3])
plotter.setLogScale(0, False)
plotter.setLogScale(1, True)
plotter.ticFont = ticFont
plotter.showStatBox = False
plotter.showKey(False)
plotter.nameX = ""
plotter.nameY = ""

if showFigures:
	plotter.visible(True)
else:
	plotter.visible(False)

""" Plots all the jhplot objects"""
plotter.cd(1,1)	
if preliminary:
	plotter.draw(prelim)
for i in range(loop):
	plotter.draw(pulse[i])
	plotter.draw(key[i])
plotter.draw(fit501)
plotter.draw(statBox501)
plotter.draw(fit604)
plotter.draw(statBox604)

plotter.cd(2,1)
for i in range(loop):
	plotter.draw(pulse[i])
	plotter.draw(fitZoom501)
	plotter.draw(fitZoom604)

plotter.cd(1,1)
theAxes_11 = plotter.getPad()
theAxes_11.setLabelSpace(0, 0.0)
theAxes_11.setLabelSpace(1, -0.01)
#theAxes_11.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, theAxes_11)
HPlotJaUtil.setTickLabelZeroPositive(theAxes_11)

plotter.cd(2,1)
theAxes_21 = plotter.getPad()
theAxes_21.setLabelSpace(0, 0.0)
theAxes_21.setLabelSpace(1, -0.01)
#theAxes_21.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, theAxes_21)
HPlotJaUtil.setTickLabelZeroPositive(theAxes_21)


""" Modifies the JaAxes and the axes labels"""
labX = plotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, plotter, 0.025)
labY = plotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, plotter, -0.01)
 

plotter.update()

""" Saves or not the plot"""
if writeFigures:
	for i in range(len(figType)):
		outFileName = outputFile + figType[i]
		plotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
		
print("That's all folks !")
if (not showFigures):
	exit()
